import dayjs from 'dayjs'
import { Request, Response, Router } from 'express'

import { randomPrice } from './constant'
import sqlQuery from '../mysql'


const router: Router = Router()

router.get('/singleList', async (req: Request, res: Response) => {
  // 需要传参数，参数从 req.query 获得
  const {
    departureAirportName,
    departureCityName,
    destinationAirportName,
    destinationCityName,
    dapartureDate,
    airCompanyName
  } = req.query

  let strSql = `SELECT * FROM flight_list`
  
  if (airCompanyName) {
    strSql = `SELECT * FROM flight_list WHERE airCompanyName = '${airCompanyName}'`
  }

  try {
    const result = await sqlQuery(strSql) as object[]
    // 模拟真实场景
    const list = result.map((item: any) => {
      return {
        ...item,
        departureAirportName,
        departureCityName,
        destinationAirportName,
        destinationCityName,
        dapartureDate,
        price: randomPrice(500, 2888),
        departureTime: dayjs(item.dptTime).format("HH:mm"),  // 出发时间
        destinationTime: dayjs(item.arrTIme).format("HH:mm")  // 到达时间
      }
    })

    res.send({
      code: 200,
      message: '请求成功',
      result: list
    })

  } catch (error) {
    res.send({
      code: 0,
      message: '请求失败'
    })
  }
})

export default router
